package io.coderyeah.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.coderyeah.basic.Result;
import io.coderyeah.org.domain.Employee;
import io.coderyeah.org.dto.EmpDTO;
import io.coderyeah.org.mapper.EmployeeMapper;
import io.coderyeah.org.service.EmployeeService;
import io.coderyeah.system.mapper.RoleMapper;
import io.coderyeah.user.domain.LoginInfo;
import io.coderyeah.user.mapper.LoginInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override

    public Result getAll(EmpDTO empDTO) {
        List<Employee> employeeList = mapper.getAll(empDTO);
        Long totals = mapper.getCount(empDTO);
        return Result.success(employeeList, totals);
    }

    @Override
    public Result editType(EmpDTO empDTO) {
        mapper.editType(empDTO.getId(), empDTO.getState() == 1 ? 0 : 1);
        return Result.success(null);
    }

    @Override
    @Transactional
    public void saveOrModify(Employee employee) {
        if (null != employee.getId()) {
            // 修改员工信息
            mapper.updateById(employee);
            // 修改登录信息
            final LoginInfo loginInfo = loginInfoMapper.selectById(employee.getLogininfoId());
            BeanUtil.copyProperties(employee, loginInfo);
            loginInfoMapper.updateById(loginInfo);
        } else {
            // 增加
            final String salt = RandomUtil.randomString(32);
            employee.setSalt(salt);
            employee.setPassword(DigestUtil.md5Hex(salt + 1));

            // 添加登录对象
            final LoginInfo loginInfo = new LoginInfo();
            BeanUtil.copyProperties(employee, loginInfo);
            loginInfo.setDisable(true);
            loginInfo.setType(0);
            loginInfoMapper.insert(loginInfo);

            // 添加员工
            employee.setLogininfoId(loginInfo.getId());
            mapper.insert(employee);

            // 添加角色
            mapper.addEmpRole(employee);

        }
    }

    @Override
    public Result getEmpsByShopId(Long shopId) {
        final List<Employee> list = mapper.selectList(new LambdaQueryWrapper<Employee>().eq(Employee::getShopId, shopId));
        return Result.success(list);
    }
}
